package cn.shop.gameapi.controller;


import cn.hutool.http.HttpUtil;
import cn.shop.gameapi.model.CodeQuery;
import cn.shop.gameapi.model.GatewaySecret;
import cn.shop.gameapi.model.MerchantGamePartition;
import cn.shop.gameapi.util.ResponseInfo;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

import static cn.shop.gameapi.model.SqlContent.*;

@RestController
@RequestMapping("/bind")
public class BindController {

    private final static Logger LOG = LoggerFactory.getLogger(BindController.class);

    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private JdbcTemplate jdbcTemplate;

    @PostMapping("/checkCode")
    public ResponseInfo<Boolean> checkCode(@RequestBody CodeQuery query) {
        MerchantGamePartition p = jdbcTemplate.queryForObject(SELECT_PARTITION, new BeanPropertyRowMapper<>(MerchantGamePartition.class), query.getPartitionId());
        if (p == null) {
            return ResponseInfo.ok(false);
        }
        String url = "http://" + p.getIp() + ":" + p.getPort() + "/gateway/api/checkCode";
        String json = "";
        try {
            json = HttpUtil.createPost(url)
                    .header("secret", getSecret(p))
                    .body(objectMapper.writeValueAsString(query))
                    .execute()
                    .body();
            LOG.info(json);
            return ResponseInfo.ok((Boolean) objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {}).get("data"));
        } catch (Exception e) {
            return ResponseInfo.ok(false);
        }
    }

    @PostMapping("/bindSuccess")
    public ResponseInfo<Map<String, Object>> bindSuccess(@RequestBody CodeQuery query) {
        MerchantGamePartition p = jdbcTemplate.queryForObject(SELECT_PARTITION, new BeanPropertyRowMapper<>(MerchantGamePartition.class), query.getPartitionId());
        if (p == null) {
            return ResponseInfo.ok();
        }
        String url = "http://" + p.getIp() + ":" + p.getPort() + "/gateway/api/bind";
        String json = "";
        try {
            json = HttpUtil.createPost(url)
                    .header("secret", getSecret(p))
                    .body(objectMapper.writeValueAsString(query))
                    .execute()
                    .body();
            LOG.info(json);
            return ResponseInfo.ok(objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {}));
        } catch (Exception e) {
            return ResponseInfo.failed("");
        }
    }

    @PostMapping("/unbind")
    public ResponseInfo<Map<String, Object>> unbind(@RequestBody CodeQuery query) {
        MerchantGamePartition p = jdbcTemplate.queryForObject(SELECT_PARTITION, new BeanPropertyRowMapper<>(MerchantGamePartition.class), query.getPartitionId());
        if (p == null) {
            return ResponseInfo.ok();
        }

        String url = "http://" + p.getIp() + ":" + p.getPort() + "/gateway/api/unbind";
        String json = "";
        try {
            json = HttpUtil.createPost(url)
                    .header("secret", getSecret(p))
                    .body(objectMapper.writeValueAsString(query))
                    .execute()
                    .body();
            LOG.info(json);
            return ResponseInfo.ok(objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {}));
        } catch (Exception e) {
            return ResponseInfo.failed("");
        }
    }

    private String getSecret(MerchantGamePartition partition) {
        GatewaySecret secret = null;
        try {
            secret = jdbcTemplate.queryForObject(SELECT_SECRET_IP, new BeanPropertyRowMapper<>(GatewaySecret.class), partition.getIp());
            return secret != null ? secret.getSecret() : null;
        } catch (EmptyResultDataAccessException ignored) {}
        return null;
    }

}
